package com.tevintao.marketingsystem.tool;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Process;
import android.util.Log;

import com.tevintao.marketingsystem.log.LogManager;
import com.tevintao.marketingsystem.shell.Shell;

import java.lang.reflect.Field;
import java.util.List;

public class PackageTool {

    /**
     * 判断APP是否已安装
     *
     * @param context
     * @param pkgName
     * @return
     */
    public static boolean isAppInstalled(Context context, String pkgName) {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(pkgName, 0);
            return pi != null;
        } catch (NameNotFoundException e) {
            Log.e("PackageTool", e.getMessage());
            e.printStackTrace();
        }
        return false;
    }

    public static String getAppVersion(Context context, String pkgName) {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(pkgName, 0);
            return pi.versionName;
        } catch (NameNotFoundException e) {
            Log.e("PackageTool", e.getMessage());
            e.printStackTrace();
        }
        return "";
    }


    public static int getAppVersionCode(Context context, String pkgName) {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(pkgName, 0);
            return pi.versionCode;
        } catch (NameNotFoundException e) {
            Log.e("PackageTool", e.getMessage());
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 通过能够PackageName启动app
     *
     * @param context
     * @param packageName
     * @return
     */
    public static boolean launchAppFormPackage(Context context, String packageName) {
        try {
            Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
            if (intent == null) {
                return false;
            }
            context.startActivity(intent);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean moveActivityFront(Context context, String packageName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> recentList = am.getRunningTasks(30);
        for (ActivityManager.RunningTaskInfo info : recentList) {
            LogManager.getInstance().logInfo(info.toString());
            if (info.topActivity.getPackageName().equals(packageName)) {
                LogManager.getInstance().logInfo(info.topActivity.toString());
                am.moveTaskToFront(info.id, 0);
                return true;
            }
        }
        return false;
    }

    public static String getAppFilePackageName(Context context, String absolutePath) {
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo info = context.getPackageManager().getPackageArchiveInfo(absolutePath, PackageManager.GET_ACTIVITIES);
            if (info != null) {
                ApplicationInfo appInfo = info.applicationInfo;
                String packageName = appInfo.packageName;  //得到安装包名称
                return packageName;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static boolean uninstall(String packageName) {
        String cmd = "pm uninstall " + packageName;
        Shell.ShellCommand command = Shell.runAsRoot(cmd);
        if (command.output != null && command.output.size() > 0 && command.output.get(command.output.size() - 1).contains("Success")) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean install(String absoluteApkPath) {
        String cmd = "pm install " + absoluteApkPath;
        Shell.ShellCommand command = Shell.runAsRoot(cmd);
        if (command.output != null && command.output.size() > 0 && command.output.get(command.output.size() - 1).contains("Success")) {
            return true;
        } else {
            return false;
        }
    }

    public static int getAppUid(Context context, String packageName) {
        ApplicationInfo applicationInfo = null;
        try {
            applicationInfo = context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return applicationInfo.uid;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }


    /**
     * 需要权限:android.permission.GET_TASKS
     *
     * @param context
     * @return
     */
    public static boolean appIsForeground(Context context, String packageName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//        String pName = am.getRunningTasks(1).get(0).topActivity.getPackageName();
//        LogManager.getInstance().logInfo("appIsForeground pName = " + pName + " topActivity = " + am.getRunningTasks(1).get(0).topActivity);
//        if (pName.equals(packageName)) {
//            return true;
//        }
//        String processName;
//        if (Build.VERSION.SDK_INT > 20) {
//            processName = am.getRunningAppProcesses().get(0).processName;
//        } else {
//            processName = am.getRunningTasks(1).get(0).topActivity.getPackageName();
//        }
        String processName = am.getRunningTasks(1).get(0).topActivity.getPackageName();
        return null != processName && processName.equals(packageName);
    }

    public static String getTopActivityName(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//        String pName = am.getRunningTasks(1).get(0).topActivity.getPackageName();
//        LogManager.getInstance().logInfo("appIsForeground pName = " + pName + " topActivity = " + am.getRunningTasks(1).get(0).topActivity);
//        if (pName.equals(packageName)) {
//            return true;
//        }
//        String processName;
//        if (Build.VERSION.SDK_INT > 20) {
//            processName = am.getRunningAppProcesses().get(0).processName;
//        } else {
//            ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
//            return cn.getClassName();
//        }


        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
//        Log.d("", "pkg:" + cn.getPackageName());
//        Log.d("", "cls:" + cn.getClassName());
        return cn.getClassName();
    }

//    public static String getTopPackageName(Context context) {
//        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
//        return cn.getPackageName();
//    }

    public static String getProcessName(Context context) {
        if (null == context) {
            LogManager.getInstance().logError("PackageTool getProcessName null == context");
            return "";
        }
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcessList = activityManager.getRunningAppProcesses();
        for (int i = 0; i < appProcessList.size(); i++) {
            ActivityManager.RunningAppProcessInfo appProcessInfo = appProcessList.get(i);
            //进程ID
            if (Process.myUid() == appProcessInfo.uid && Process.myPid() == appProcessInfo.pid) {
                return appProcessInfo.processName;
            }
        }
        return "";
    }

    public static void stopApp(final String packageName) {
        String command = "am force-stop " + packageName;
        Shell.runAsRoot(command);
    }

    public static boolean alive(Context context, String packageName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> processes = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo info : processes) {
            for (String pName : info.pkgList) {
                if (pName.equals(packageName)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean aliveMore5(Context context, String packageName) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ProcessManager.Process> runningApps = ProcessManager.getRunningApps();
            for (ProcessManager.Process process : runningApps) {
//                LogManager.getInstance().logInfo(process.getPackageName() + "" + process.name + " " + process.user + " " + process.uid + " " + process.pid);
                if (null != process && null != process.getPackageName() && process.getPackageName().equals(packageName)) {
                    return true;
                }
            }
            return false;
        } else {
            return alive(context, packageName);
        }
    }

    public static Context getResolverContext(ContentResolver resolver) {
        if (null == resolver) {
            return null;
        }
        try {
            Field mContextField = ContentResolver.class.getDeclaredField("mContext");
            LogManager.getInstance().logInfo("mContextField = " + mContextField);
            mContextField.setAccessible(true);
            return (Context) mContextField.get(resolver);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            LogManager.getInstance().logError("getResolverContext NoSuchFieldException");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            LogManager.getInstance().logError("getResolverContext IllegalAccessException");
        }
        return null;
    }

    private int getAppVersion(Context context) {
        if (null == context) {
            return -1;
        }
        PackageManager pckMan = context.getPackageManager();
        try {
            PackageInfo packageInfo = pckMan.getPackageInfo("com.tevintao.marketingsystem", 0);
            if (null != packageInfo) {
                return packageInfo.versionCode;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            Log.e("ttw", "PackageManager.NameNotFoundException com.tevintao.marketingsystem");
        }
        return -1;
    }
}
